﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Enumeration;
using System.Xml.Serialization;
using UnityEngine;

public class XMLDataManager
{
    private static XMLDataManager instance=new XMLDataManager();
    public static XMLDataManager Instance
    {
        get
        { 
            return instance;
        }
    }

    private XMLDataManager() { }

    public void SaveData(object obj, string fileName)
    {
        string path = Application.persistentDataPath + '/' + fileName + ".xml";
        using (StreamWriter sw = new StreamWriter(path))
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            xs.Serialize(sw, obj);
        }
    }

    public object LoadData(Type type, string fileName)
    {
        string path = Application.persistentDataPath + '/' + fileName + ".xml";

        if (!File.Exists(path))
        { 
            path = Application.streamingAssetsPath + '/' + fileName + ".xml";
            //如果文件都不存在，就返回一个对象的默认值
            if (!File.Exists(path))
            {
                return Activator.CreateInstance(type);
            }
        }

        using (StreamReader sr = new StreamReader(path))
        { 
            XmlSerializer xs = new XmlSerializer (type);
            return xs.Deserialize(sr);
        }

    }
}
